<template>
  <div>
    <test t1="商品管理" t2="分类参数" path="/home">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器组件 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            placeholder="请选择"
            show-all-levels
            @change="parentCateChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addParams">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 展示 tag 标签 -->
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加 tag 标签输入框 -->
                <!-- native 是事件修饰符，让事件以原生事件的方式触发 -->
                <!-- 因为在组件上绑定的所有事件都认为是自定义事件，哪怕是个原生click事件 -->
                <!-- 所以要想触发原生事件，必须添加事件修饰符 native -->
                <!-- element-ui 在底层使用 $listener 监听了大部分原生事件，所以绑定被监听的原生事件时不需要加 native 事件修饰符 -->
                <!-- 还有一些没被监听，比如所有键盘的按键事件，绑定这些事件时，必须添加 native 事件修饰符才能出发 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加 new tag 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="item in scope.row.attr_vals" :key="item.attr_id">{{item}}</el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </test>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeResetAddParams"
    >
      <el-form
        :model="addForm"
        :rules="FormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeResetEditParams"
    >
      <el-form
        :model="editForm"
        :rules="FormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类列表数据
      cateList: [],
      // 被选中的分类节点所在的各级菜单的值所组成的数组
      selectedKeys: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        // label 表示将选项名称指定为选项对象的哪一个属性值
        label: "cat_name",
        // value 表示将选项的值指定为选项对象的哪一个属性值
        value: "cat_id",
        // children 表示将选项的子选项指定为选项对象的哪一个属性值
        children: "children",
        // expandTrigger 表示要以何种方式触发次级菜单的展开
        expandTrigger: "hover",
        // checkStrictly 设置为 true 表示将父子节点解除关联，即可以选择任意节点，默认为 false，只能选择最后一级节点
        checkStrictly: false,
        // emitPath 表示在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值,默认为true
        emitPath: true
      },
      // 被选中选项卡的 name 值，默认为第一个选项卡的 name 值
      activeName: "many",
      // 动态参数表格数据
      manyTableData: [],
      // 静态属性表格数据
      onlyTableData: [],
      // 添加参数表单数据
      addForm: {
        attr_name: ""
      },
      // 添加表单的验证规则对象
      FormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      // 控制添加参数对话框的显示隐藏
      addDialogVisible: false,
      // 控制编辑参数对话框的显示隐藏
      editDialogVisible: false,
      // 编辑参数表单数据
      editForm: {}
    };
  },
  methods: {
    // 获取分类列表
    async getCatesList() {
      const { data: res } = await this.$axios.get("categories");
      //   console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("获取分类列表数据失败！");
      this.cateList = res.data;
    },
    // 级联选择器选项发生变化时触发
    parentCateChanged() {
      // console.log(this.selectedKeys);
      this.getParamsData();
    },
    // tab 栏切换时触发
    handleClick() {
      this.getParamsData();
    },
    // 获取参数的列表数据
    async getParamsData() {
      if (this.selectedKeys.length != 3) {
        this.selectedKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      const { data: res } = await this.$axios.get(
        `categories/${this.catId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      //   console.log(res);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        // 为每个 item 参数对象动态添加两个属性，为后续开发添加 tag 功能做准备
        // 双向绑定输入框的值，默认为空
        item.inputValue = "";
        // 控制输入框的显示隐藏
        item.inputVisible = false;
        // console.log(tag);
      });
      if (this.activeName == "many") {
        this.manyTableData = res.data;
        // console.log(res.data);
      } else {
        this.onlyTableData = res.data;
        // console.log(res.data);
      }
    },
    // 点击添加参数按钮
    addParams() {
      this.addDialogVisible = true;
    },
    // 关闭添加参数对话框重置表单数据
    closeResetAddParams() {
      this.$refs.addFormRef.resetFields();
      this.addDialogVisible = false;
    },
    // 添加参数表单提交
    submitAddForm() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$axios.post(
          `categories/${this.catId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status != 201)
          return this.$message.error("添加参数失败！");
        this.$message.success("添加参数成功！");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // 点击编辑参数按钮
    async editParams(attrId) {
      const { data: res } = await this.$axios.get(
        `categories/${this.catId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      );
      // console.log(res);
      if (res.meta.status != 200) return this.$message.error("获取参数失败！");
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 编辑表单提交
    submitEditForm() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        // console.log(this.editForm);
        const { data: res } = await this.$axios.put(
          `categories/${this.catId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.editForm.attr_vals
          }
        );
        // console.log(res);
        if (res.meta.status != 200)
          return this.$message.error("修改参数失败！");
        this.$message.success(res.meta.msg);
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    // 关闭编辑参数对话框重置表单数据
    closeResetEditParams() {
      this.$refs.editFormRef.resetFields();
      this.editForm = {};
    },
    // 点击删除按钮
    async deleteParams(attrId) {
      const confirmResult = await this.$confirm(
        "您确定要永久删除该参数吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult == "cancel")
        return this.$message({ type: "info", message: "已取消删除!" });
      const { data: res } = await this.$axios.delete(
        `categories/${this.catId}/attributes/${attrId}`
      );
      if (res.meta.status != 200) return this.$message.error("删除参数失败！");
      this.$message.success("删除参数成功！");
      this.getParamsData();
    },
    // 删除 Tag 标签时触发
    handleClose(index, row) {
      //   console.log(index, row);
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
    // 点击添加新 tag 标签时，显示输入框
    showInput(row) {
      row.inputVisible = true;
      // 由 new tag 按钮 变成 input 输入框时，会触发页面重绘
      // $nextTick 方法的作用，就是当页面重绘后，才会指定回调函数中的代码
      // this.$refs.saveTagInput 获取到的是 el-input 组件对象
      // 通过 el-input.$refs.input 获取到的是其内部的 input 元素对象
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 输入完毕或者失去焦点时触发
    handleInputConfirm(row) {
      // console.log(row);
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue.trim());
        this.saveAttrVals(row);
      }
      row.inputVisible = false;
      row.inputValue = "";
    },
    // 将对 attr_vals 的操作，将其保存到数据库
    async saveAttrVals(row) {
      const { data: res } = await this.$axios.put(
        `categories/${this.catId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(",")
        }
      );
      //   console.log(res);
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    }
  },
  created() {
    this.getCatesList();
  },
  computed: {
    // 如果添加参数按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled() {
      if (this.selectedKeys.length != 3) {
        return true;
      }
      return false;
    },
    // 当前选中的三级分类的Id
    catId() {
      if (this.selectedKeys.length == 3) {
        return this.selectedKeys[2];
      }
      return null;
    },
    // 动态计算标题的文本
    titleText() {
      if (this.activeName == "many") return "动态参数";
      return "静态属性";
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  width: 25%;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>